﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Xml.Linq;
using System.IO;

/// <summary>
///WeiXinRec 的摘要说明
/// </summary>
/// 
namespace WeiXin
{
    public class MsgRec
    {
        public MsgRec()
        {
            string postStr = "";
            if (System.Web.HttpContext.Current.Request.HttpMethod.ToLower() == "post")
            {
                postStr = PostInput();  //获取POST返回来的数据
                if (false == string.IsNullOrWhiteSpace(postStr))
                {
                    try
                    {
                        var xDoc = XDocument.Parse(postStr);
                        var q = (from c in xDoc.Elements() select c).ToList();
                        var msgType = q.Elements("MsgType").First().Value; // 获取信息内容的类型

                        //建立工厂对象处理回复类型
                        MsgManageFactory mf = new MsgManageFactory();
                        MsgManage autoResponse = null;
                        switch (msgType)
                        {
                            case "text":
                                autoResponse = mf.MakeTextMsgManage(postStr);
                                break;
                            case "image":
                                break;
                            case "location":
                                break;
                            case "link":
                                break;
                            case "event":
                                break;
                            default: break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                        //Log.WriteLog("错误位于MsgRec : 接收处理异常" + ex.ToString());
                    }
                }
            }
        }

        /// <summary>  
        /// 获取POST返回来的数据   -   xml字符串
        /// </summary>  
        /// <returns></returns>  
        private string PostInput()
        {
            try
            {
                System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
                int count = 0;
                byte[] buffer = new byte[s.Length];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
                {
                    builder.Append(System.Web.HttpContext.Current.Request.ContentEncoding.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                return builder.ToString();
            }
            catch (Exception ex)
            { throw ex; }
        }
    }
}